<template>
  <section>
    <textarea ref="code"></textarea>
  </section>
</template>
<script>
  let CodeMirror = require("codemirror/lib/codemirror");
  
  import "codemirror/mode/sql/sql";
  import "codemirror/lib/codemirror.css";
  import "codemirror/addon/hint/show-hint.css";

  require("codemirror/mode/sql/sql");
  require("codemirror/addon/hint/show-hint");
  require("codemirror/addon/hint/sql-hint");

  import sqlFormatter from "sql-formatter";

  export default {
    name: "CodeEditor",
    props: {
      code: {
        type: String,
        default: ""
      },
      language: {
        type: String,
        default: "text/x-sql"
      }
    },
    components: {},
    data() {
      return {
        editor: null,
        value: ""
      };
    },
    computed: {},
    watch: {
      code(value) {
        this.editor.setValue(sqlFormatter.format(value));
      }
    },
    methods: {
      init() {
        let that = this;
        that.editor = CodeMirror.fromTextArea(that.$refs.code, {
          mode: that.language,
          firstLineNumber: 1,
          showCursorWhenSelecting: true,
          lineNumbers: false, // 显示行号
          smartIndent: true, //智能缩进
          indentUnit: 4, // 智能缩进单位为4个空格长度
          indentWithTabs: true, // 使用制表符进行智能缩进
          lineWrapping: true, //
          foldGutter: true, // 启用行槽中的代码折叠
          autofocus: true, //自动聚焦
          matchBrackets: true, // 匹配结束符号，比如"]、}"
          autoCloseBrackets: true // 自动闭合符号
        });
        that.editor.on("keyup", function(cm, event) {
          if (
            !cm.state.completionActive &&
            ((event.keyCode >= 65 && event.keyCode <= 90) ||
              event.keyCode == 52 ||
              event.keyCode == 219 ||
              event.keyCode == 190)
          ) {
            CodeMirror.commands.autocomplete(cm, null, {
              completeSingle: false
            });
          }
        });
      },
      setValue(value) {
        this.value = value;
        this.editor.setValue(sqlFormatter.format(value));
      }
    },
    mounted() {
      this.init();
      this.setValue(this.code);
    }
  };
</script>
<style lang="less" scoped>
  /deep/ .CodeMirror {
    border: 1px solid #dcdfe6;
  }
</style>
